import React from 'react'
import { Button, Form, Input, Card, Space, message } from 'antd'
import { useNavigate, useParams, useLocation } from 'react-router-dom'
import {
  reqAddHospitalSet,
  reqUpdateHospitalSet,
} from '@api/hospital/hospitalSet'
import { IhospitalSetItem } from '@api/hospital/hospitalSet/model/hospitalSettypes'
export default function HospitalSetAddOrUpdate() {
  // 1. 获取id
  const { id } = useParams()
  // 2. 获取当前要修改的医院的数据,并渲染到表单中
  const hospitalSet = useLocation().state as IhospitalSetItem

  // 3. 将传递过来的数据,渲染到表单当中
  const [form] = Form.useForm()
  form.setFieldsValue(hospitalSet) // {hosname:值, hoscode:值}
  const navigate = useNavigate()

  // 提交按钮的事件处理函数
  const onFinish = async (values: any) => {
    // 判断当前是添加还是修改
    // 如果是添加则id为undefined.如果是修改id一定有值
    if (id) {
      //修改
      //values中只有表单中的数据,所以要记得把id添加到values的对象里面
      values.id = id
      await reqUpdateHospitalSet(values)
      message.success('修改医院设置成功')
    } else {
      // 添加
      // 发送请求,添加数据
      await reqAddHospitalSet(values)
      // 提示用户,添加成功
      message.success('添加医院设置成功')
    }
    // 回到医院设置页面
    navigate(-1)
  }

  return (
    <Card>
      <Form
        form={form}
        name="basic"
        onFinish={onFinish}
        labelCol={{ span: 2 }}
        // wrapperCol={{ offset: 3 }}
      >
        <Form.Item
          label="医院名称"
          name="hosname"
          rules={[{ required: true, message: 'Please input your hosname!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="医院编码"
          name="hoscode"
          rules={[{ required: true, message: 'Please input your hoscode!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="api基础路径"
          name="apiUrl"
          rules={[{ required: true, message: 'Please input your apiUrl!' }]}
        >
          <Input></Input>
        </Form.Item>
        <Form.Item
          label="联系人名称"
          name="contactsName"
          rules={[
            { required: true, message: 'Please input your contactsName!' },
          ]}
        >
          <Input></Input>
        </Form.Item>
        <Form.Item
          label="联系人手机"
          name="contactsPhone"
          rules={[
            {
              required: true,
              message: 'Please input your contactsPhone!',
              pattern: /^1[3-9]\d{9}$/,
            },
          ]}
        >
          <Input></Input>
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 2 }}>
          <Space>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
            <Button
              onClick={() => {
                navigate(-1)
              }}
            >
              返回
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  )
}
